package com.ruoyi.purchase.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.purchase.domain.ProcOrder;
import com.ruoyi.purchase.service.IProcOrderService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.RoleUtils;
import com.ruoyi.basedata.service.IBaseSupplierService;
import com.ruoyi.basedata.domain.BaseSupplier;
import com.ruoyi.basedata.service.IBaseProductService;
import com.ruoyi.basedata.domain.BaseProduct;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.common.core.domain.entity.SysDictData;

/**
 * 采购订单主Controller
 * 
 * @author ruoyi
 * @date 2025-06-17
 */
@Controller
@RequestMapping("/purchase/order")
public class ProcOrderController extends BaseController
{
    private String prefix = "purchase/order";

    @Autowired
    private IProcOrderService procOrderService;
    
    @Autowired
    private IBaseSupplierService baseSupplierService;
    
    @Autowired
    private IBaseProductService baseProductService;
    
    @Autowired
    private ISysDictDataService dictDataService;

    @RequiresPermissions("purchase:order:view")
    @GetMapping()
    public String order()
    {
        return prefix + "/order";
    }

    /**
     * 查询采购订单主列表
     */
    @RequiresPermissions("purchase:order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ProcOrder procOrder)
    {
        // 设置当前登录用户名，用于数据权限控制
        Map<String, Object> params = new HashMap<>();
        params.put("loginName", ShiroUtils.getLoginName());
        
        // 判断是否为审核员
        boolean isAuditor = RoleUtils.isAuditor();
        params.put("isAuditor", isAuditor);
        
        // 判断是否为总负责人
        boolean isChief = RoleUtils.isChief();
        params.put("isChief", isChief);
        
        // 总负责人只能看到审核通过的数据
        if (isChief) {
            procOrder.setAuditStatus("1"); // 审核通过
        }
        
        procOrder.setParams(params);
        
        startPage();
        List<ProcOrder> list = procOrderService.selectProcOrderList(procOrder);
        return getDataTable(list);
    }

    /**
     * 导出采购订单主列表
     */
    @RequiresPermissions("purchase:order:export")
    @Log(title = "采购订单主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ProcOrder procOrder)
    {
        List<ProcOrder> list = procOrderService.selectProcOrderList(procOrder);
        ExcelUtil<ProcOrder> util = new ExcelUtil<ProcOrder>(ProcOrder.class);
        return util.exportExcel(list, "采购订单主数据");
    }

    /**
     * 新增采购订单主
     */
    @RequiresPermissions("purchase:order:add")
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        // 自动生成订单编号
        String orderCode = com.ruoyi.purchase.utils.OrderCodeGenerator.generateOrderCode();
        mmap.put("orderCode", orderCode);
        
        // 查询所有可用的供应商列表
        BaseSupplier baseSupplier = new BaseSupplier();
        baseSupplier.setStatus("0"); // 0表示正常状态的供应商
        List<BaseSupplier> supplierList = baseSupplierService.selectBaseSupplierList(baseSupplier);
        mmap.put("supplierList", supplierList);
        
        // 查询所有正常状态的商品列表
        BaseProduct baseProduct = new BaseProduct();
        baseProduct.setStatus("0"); // 0表示正常状态的商品
        List<BaseProduct> productList = baseProductService.selectBaseProductList(baseProduct);
        mmap.put("productList", productList);
        
        // 获取商品类别字典数据
        SysDictData dictData = new SysDictData();
        dictData.setDictType("product_category");
        List<SysDictData> categoryList = dictDataService.selectDictDataList(dictData);
        mmap.put("categoryList", categoryList);
        
        // 将当前登录用户名添加到session中
        String loginName = ShiroUtils.getLoginName();
        getRequest().getSession().setAttribute("loginName", loginName);
        
        return prefix + "/add";
    }

    /**
     * 新增保存采购订单主
     */
    @RequiresPermissions("purchase:order:add")
    @Log(title = "采购订单主", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ProcOrder procOrder)
    {
        // 确保设置创建者和更新者
        String loginName = ShiroUtils.getLoginName();
        procOrder.setCreatedBy(loginName);
        procOrder.setUpdatedBy(loginName);
        return toAjax(procOrderService.insertProcOrder(procOrder));
    }

    /**
     * 修改采购订单主
     */
    @RequiresPermissions("purchase:order:edit")
    @GetMapping("/edit/{orderId}")
    public String edit(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        ProcOrder procOrder = procOrderService.selectProcOrderByOrderId(orderId);
        mmap.put("procOrder", procOrder);
        
        // 查询所有可用的供应商列表
        BaseSupplier baseSupplier = new BaseSupplier();
        baseSupplier.setStatus("0"); // 0表示正常状态的供应商
        List<BaseSupplier> supplierList = baseSupplierService.selectBaseSupplierList(baseSupplier);
        mmap.put("supplierList", supplierList);
        
        // 查询所有正常状态的商品列表
        BaseProduct baseProduct = new BaseProduct();
        baseProduct.setStatus("0"); // 0表示正常状态的商品
        List<BaseProduct> productList = baseProductService.selectBaseProductList(baseProduct);
        mmap.put("productList", productList);
        
        // 获取商品类别字典数据
        SysDictData dictData = new SysDictData();
        dictData.setDictType("product_category");
        List<SysDictData> categoryList = dictDataService.selectDictDataList(dictData);
        mmap.put("categoryList", categoryList);
        
        // 将当前登录用户名添加到session中
        String loginName = ShiroUtils.getLoginName();
        getRequest().getSession().setAttribute("loginName", loginName);
        
        return prefix + "/edit";
    }

    /**
     * 修改保存采购订单主
     */
    @RequiresPermissions("purchase:order:edit")
    @Log(title = "采购订单主", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ProcOrder procOrder)
    {
        // 普通用户不能修改订单状态和审核状态
        ProcOrder existingOrder = procOrderService.selectProcOrderByOrderId(procOrder.getOrderId());
        procOrder.setStatus(existingOrder.getStatus());
        procOrder.setAuditStatus(existingOrder.getAuditStatus());
        
        // 确保设置更新者
        String loginName = ShiroUtils.getLoginName();
        procOrder.setUpdatedBy(loginName);
        
        return toAjax(procOrderService.updateProcOrder(procOrder));
    }

    /**
     * 删除采购订单主
     */
    @RequiresPermissions("purchase:order:remove")
    @Log(title = "采购订单主", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(procOrderService.deleteProcOrderByOrderIds(ids));
    }
    
    /**
     * 获取供应商列表
     */
    @GetMapping("/supplierList")
    @ResponseBody
    public AjaxResult getSupplierList()
    {
        BaseSupplier baseSupplier = new BaseSupplier();
        baseSupplier.setStatus("0"); // 0表示正常状态
        List<BaseSupplier> supplierList = baseSupplierService.selectBaseSupplierList(baseSupplier);
        return AjaxResult.success(supplierList);
    }
    
    /**
     * 获取商品列表
     */
    @GetMapping("/productList")
    @ResponseBody
    public AjaxResult getProductList()
    {
        BaseProduct baseProduct = new BaseProduct();
        baseProduct.setStatus("0"); // 0表示正常状态
        List<BaseProduct> productList = baseProductService.selectBaseProductList(baseProduct);
        return AjaxResult.success(productList);
    }
}
